@Controller
@RequestMapping("/student")
public class StudentController {
    
    @Autowired
    private StudentService studentService;
    
    @GetMapping("/list")
    public String listStudents(
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "name", required = false) String name,
            Model model) {
        
        PageInfo<StudentVO> pageInfo = studentService.getStudentList(page, size, name);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("name", name);
        
        return "student/list";
    }
    
    @GetMapping("/add")
    public String addStudentForm(Model model) {
        model.addAttribute("student", new StudentDTO());
        return "student/form";
    }
    
    @PostMapping("/save")
    public String saveStudent(@Valid StudentDTO studentDTO, BindingResult result) {
        if (result.hasErrors()) {
            return "student/form";
        }
        
        studentService.saveStudent(studentDTO);
        return "redirect:/student/list";
    }
    
    @GetMapping("/edit/{id}")
    public String editStudentForm(@PathVariable Long id, Model model) {
        StudentDTO studentDTO = studentService.getStudentById(id);
        model.addAttribute("student", studentDTO);
        return "student/form";
    }
    
    @GetMapping("/delete/{id}")
    public String deleteStudent(@PathVariable Long id) {
        studentService.deleteStudent(id);
        return "redirect:/student/list";
    }
}